'use strict'

$(function () {
    $.get('http://localhost:8080/product', (data) => {
        render(data)
    })
})
// 显示页面数据
function render(arr) {
    let row = $('.rowData')
    let tb = $('#tb')
    row.remove()
    arr.forEach(item => {
        let html = `
            <tr class="rowData">
                <td>${item.id}</td>
                <td>${item.name}</td>
                <td>${item.price}</td>
                <td>${item.stock}</td>
                <td>${item.supplier}</td>
                <td>
                    <input type="button" value="编辑" onclick="Edit(${item.id})">
                    <input type="button" value="删除" onclick="Delete(${item.id})">
                </td>
            </tr>
        `
        tb.append(html)
    })
}
function getJsonResutlt() {
    return new Promise(function (res, rej) {
        $.get(`http://localhost:8080/product`, data => {
            res(data)
        })
    })
}
// 查找
function Query() {
    let keyword = $('#keyword').val()
    getJsonResutlt().then(data => {
        if (keyword) {
            let arr = data.filter(item => {
                return item.id == keyword || item.name == keyword || item.price == keyword ||
                    item.stock == keyword || item.supplier == keyword
            })
            render(arr)
        } else {
            render(data)
        }
    })
}
// 新增
function add() {
    location.href = './add.html'
}
// 新增保存按钮
function refer() {
    let name = $('[name=name]').val(),
        price = $('[name=price]').val(),
        stock = $('[name = stock]').val(),
        supplier = $('[name=supplier]').val()
    let obj = {
        name, price, stock, supplier
    }
    $.post('http://localhost:8080/product', obj, data => {
        render(data)
        location.href = './index.html'
    })
}
// 新增取消按钮
function cancel() {
    location.href = './index.html'
}

// 删除
function Delete(id) {
    $.ajax({
        type: 'delete',
        url: `http://localhost:8080/product/${id}`,
        success: data => {
            render(data)
        }
    })
}

// 编辑
function Edit(id) {
    location.href = `./Edit.html?${id}`
}
// 编辑保存
function save() {
    let obj = {
        id:$('[name=id]').val(),
        name:$('[name=name]').val(),
        price:$('[name=price]').val(),
        stock:$('[name=stock]').val(),
        supplier:$('[name=supplier]').val()
    }
    console.log(obj);
    $.ajax({
        url:`http://localhost:8080/product`,
        type:'put',
        data:obj,
        success:data=>{
            console.log(data);
            render(data)
            location.href='./index.html'
        }
    })
}